package com.example.controller;

import com.example.domain.Type;
import com.example.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @className: TypeController
 * @author: Joe
 * @create: 2023-02-07 08:44
 * @description:分类服务
 */
@CrossOrigin
@RestController
@RequestMapping("/type")
public class TypeController {
    @Autowired
    TypeService typeService;
    public static final String list="types";
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 从缓存获取列表
     * @return
     */
    @RequestMapping("/list")
    public List<Type> list(){
        if (!redisTemplate.hasKey(list)){
            //判断是否存在
            redisTemplate.opsForList().rightPushAll(list,typeService.list());
        }
        return redisTemplate.opsForList().range(list,0,-1);
    }

    /**
     * 考虑缓存同步策略
     * @param type
     */
    @RequestMapping("/add")
    public void add(@RequestBody Type type){
       typeService.save(type);
       redisTemplate.delete(list);
    }
}
